<?php

function fertilizer_case_add_page($id) {
    return drupal_get_form('fertilizer_case_edit_form',$id);
}

function fertilizer_case_edit_page($id) {
    return drupal_get_form('fertilizer_case_edit_form', $id);
}

function fertilizer_case_edit_form($form, &$form_state) {
    if (!empty($_GET['farmer_id'])) {
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if (!empty($form_state['farmer'])) {
        $form['#farmer'] = $form_state['farmer'];
    }
    drupal_add_js(drupal_get_path('module', 'fertilizer_case') .'/fertilizer_case_add_sub_extra.js', 'file');
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('fertilizer_case', 'fertilizer_case_id', $id);
        if (empty($record)) {
            drupal_set_message(t('施肥案例不存在！'), 'status', FALSE);
            return $form;
        }
        $form['#fertilizer_case_id'] = $id;
    }

    $form['submit_id'] = array(
        '#type' => 'hidden',
    );
    // 判断用户角色
    if(!nonghua_user_access('fertilizer_case', 'view', $id, !empty($record) ? $record->author_uid:0, $record->farmer_id) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    insert_fertilizer_sub_info($form,$form_state,'fertilizer_case_extra');

    $form['dif_column_id'] = array(
        '#type' => 'hidden',
        '#default_value' => !empty($record)?$record->fertilizer_case_id:''
    );
    _insert_farmer_select_info($form,$form_state,$record);
    $form['effect_desc'] = array(
        '#type' => 'textarea',
        '#title' => '效果描述',
        '#default_value' => !empty($record) ? $record->effect_desc : '',
        '#size' => 32,
        '#maxlength' => 500,
        '#attributes'=>array('placeholder'=>'最多输入500字。')
    );
//    $form['real_yield'] = array(
//        '#type' => 'textfield',
//        '#title' => '实际产量',
//        '#default_value' => !empty($record) ? $record->real_yield : '0',
//    );
    insert_special_activities($form,$form_state,isset($record) && !empty($record)?$record:'');
    $form['plant'] = _insert_plant_selection_form($form,$form_state,!empty($record) ? $record->plant_id:'');
//    _insert_plant_selection_form($form,$form_state,!empty($record) ? $record->plant_id:'');
//    $form['basic_info']['rec_plant_id']=
    $form['fertilization']['#value'] =  fertilization_list('fertilizer_case_extra','fertilizer_case_id',$id);
//    if(!empty($record)){
        $file_ids = get_file_ids($record->fertilizer_case_id);
        foreach($file_ids as $F_k => $F_v){
            if(!empty($F_v)){
                $form['files']['#value'][$F_k]= file_load($F_v);
            }
        }
//    }
//    print_r($file_ids);die;

    $form['#attributes']['enctype'] = 'multipart/form-data';
    $form['file_upload1'] = array(
        '#type' => 'managed_file',
        '#title' => t('Company Logo'),
//        '#description' => t('Allowed extensions: gif png jpg jpeg'),
        '#upload_location' => 'public://',
        '#default_value' => $file_ids->file_id1,
        '#theme' => 'nonghua_common_thumb_upload',
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            // Pass the maximum file size in bytes
            'file_validate_size' => array(1024*1024*1024),
        ),
    );
    $form['file_upload2'] = array(
        '#type' => 'managed_file',
        '#title' => t('Company Logo'),
//        '#description' => t('Allowed extensions: gif png jpg jpeg'),
        '#upload_location' => 'public://',
        '#default_value' =>$file_ids->file_id2,
        '#theme' => 'nonghua_common_thumb_upload',
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            // Pass the maximum file size in bytes
            'file_validate_size' => array(1024*1024*1024),
        ),
    );
    $form['file_upload3'] = array(
        '#type' => 'managed_file',
        '#title' => t('Company Logo'),
//        '#description' => t('Allowed extensions: gif png jpg jpeg'),
        '#upload_location' => 'public://',
        '#default_value' => $file_ids->file_id3,
        '#theme' => 'nonghua_common_thumb_upload',
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            // Pass the maximum file size in bytes
            'file_validate_size' => array(1024*1024*1024),
        ),
    );
    $form['file_upload4'] = array(
        '#type' => 'managed_file',
        '#title' => t('Company Logo'),
//        '#description' => t('Allowed extensions: gif png jpg jpeg'),
        '#upload_location' => 'public://',
        '#default_value' => $file_ids->file_id4,
        '#theme' => 'nonghua_common_thumb_upload',
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            // Pass the maximum file size in bytes
            'file_validate_size' => array(1024*1024*1024),
        ),
    );
    $form['file_upload5'] = array(
        '#type' => 'managed_file',
        '#title' => t('Company Logo'),
//        '#description' => t('Allowed extensions: gif png jpg jpeg'),
        '#upload_location' => 'public://',
        '#default_value' => $file_ids->file_id5,
        '#theme' => 'nonghua_common_thumb_upload',
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            // Pass the maximum file size in bytes
            'file_validate_size' => array(1024*1024*1024),
        ),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => arg(1) === 'edit' ? '修改' : '添加',
        '#access' => nonghua_user_access('fertilizer_case', 'edit', $id, !empty($record) ? $record->author_uid:0,$record->farmer_id)
    );
    return $form;
}

function fertilizer_case_edit_form_validate($form, &$form_state) {

    if(!empty($form_state['values']['real_yield'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['real_yield']) || (strlen(explode('.',$form_state['values']['real_yield'])[0])>8)) {
            form_set_error('real_yield',  "实际产量格式错误");
        }
    }
    if(!empty($form_state['values']['population'])){
        $reg = '/^\d{1,10}$/';
        if(!preg_match ($reg, $form_state['values']['population'])) {
            form_set_error('population', "人口数量格式错误");
        }
    }
//    if(empty($form_state['values']['fertilizer_case'])){
//        form_set_error('fertilizer_case', '必须填写 施肥案例');
//    }else if(!isset($form_state['build_info']['args'][0])){
//        $record = db_select('fertilizer_case', 'u')
//            ->condition('u.addr_id', $form_state['values']['fertilizer_case'])
//            ->fields('u')
//            ->execute()->fetchAssoc();
//        if (!empty($record)) {
//            form_set_error('fertilizer_case', "该施肥案例信息已存在！");
//        }
//    }
    if(empty($form_state['values']['plant'])){
        form_set_error('plant', '必须填写 农作物');
    }
    if(empty($form_state['values']['farmer_id'])){
        form_set_error('select_farmer_button', '必须选择 农户');
    }
    if(!empty($form_state['values']['plant'])){
        $plant_id = get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false);
        if(empty($plant_id)){
            form_set_error('plant', "作物信息不存在！");
        }
    }
}

function fertilizer_case_edit_form_submit($form, &$form_state) {
    global $user;
//    print_r($form_state);die;
//    $file1 = file_save_upload('file_upload1',NULL,'public://');
//    $file2 = file_save_upload('file_upload2',NULL,'public://');
//    $file3 = file_save_upload('file_upload3',NULL,'public://');
//    $file4 = file_save_upload('file_upload4',NULL,'public://');
//    $file5 = file_save_upload('file_upload5',NULL,'public://');
//    file_delete(stdClass)
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    $address = _get_address_id($form_state);
    $transaction = db_transaction();
    try {
        if (arg(1) == 'add') { //add new fertilizer_case
            $nid = db_insert('fertilizer_case') // Table name no longer needs {}
            ->fields(array(
                'farmer_id' => $form_state['values']['farmer_id'],
                'plant_id' => get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false),
                'effect_desc' => $form_state['values']['effect_desc'],
//                'real_yield' => $form_state['values']['real_yield'],
                'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                'file_id1'=>!empty($form_state['values']['file_upload1'])?$form_state['values']['file_upload1']:NULL,
                'file_id2'=>!empty($form_state['values']['file_upload2'])?$form_state['values']['file_upload2']:NULL,
                'file_id3'=>!empty($form_state['values']['file_upload3'])?$form_state['values']['file_upload3']:NULL,
                'file_id4'=>!empty($form_state['values']['file_upload4'])?$form_state['values']['file_upload4']:NULL,
                'file_id5'=>!empty($form_state['values']['file_upload5'])?$form_state['values']['file_upload5']:NULL,
                'author_uid' => $form_state['values']['farmer_id'],
                'timestamp' => time(),))
                ->execute();
            if ($nid > 0) {
                $ids = explode(',',$form_state['values']['submit_id']);
                _update_fertilizer_extra($nid,$ids,"fertilizer_case_extra","fertilizer_case_id");
                drupal_set_message(t('添加成功！'), 'status', FALSE);
                if(!empty($_GET['farmer_id'])){
                    drupal_goto('fertilizer_case/add/'.$nid,array('query' => array('farmer_id' => $_GET['farmer_id'])));
                }
                if(!empty($_GET['addr_id'])){
                    drupal_goto('fertilizer_case/list',array('query' => array('addr_id' => $_GET['addr_id'])));
                }
                drupal_goto('fertilizer_case/add');
            }

        } else {
            $file_ids = get_file_ids($id);
            $nid = db_update('fertilizer_case')// edit exsting store. todo: update only modified fields
            ->fields(array(
                'farmer_id' => $form_state['values']['farmer_id'],
                'plant_id' => get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false),
                'effect_desc' => $form_state['values']['effect_desc'],
//                'real_yield' => $form_state['values']['real_yield'],
                'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
//                'author_uid' => $user->uid,
                'file_id1'=>!empty($form_state['values']['file_upload1'])?$form_state['values']['file_upload1']:$file_ids->file_id1,
                'file_id2'=>!empty($form_state['values']['file_upload2'])?$form_state['values']['file_upload2']:$file_ids->file_id2,
                'file_id3'=>!empty($form_state['values']['file_upload3'])?$form_state['values']['file_upload3']:$file_ids->file_id3,
                'file_id4'=>!empty($form_state['values']['file_upload4'])?$form_state['values']['file_upload4']:$file_ids->file_id4,
                'file_id5'=>!empty($form_state['values']['file_upload5'])?$form_state['values']['file_upload5']:$file_ids->file_id5,
                'timestamp' => time(),))
                ->condition('fertilizer_case_id', $id, '=')
                ->execute();
            if ($nid > 0) {
                drupal_set_message(t('修改成功！'), 'status', FALSE);
            }
            if(!empty($_GET['farmer_id'])){
                drupal_goto('fertilizer_case/list',array('query' => array('farmer_id' => $_GET['farmer_id'])));
            }
            if(!empty($_GET['addr_id'])){
                drupal_goto('fertilizer_case/list',array('query' => array('addr_id' => $_GET['addr_id'])));
            }

        }
    }catch (Exception $e){
        $transaction->rollback();
        watchdog_exception('fertilizer_case', $e);
        throw $e;
    }

}

function get_file_ids($id){
    $query = db_select('fertilizer_case','FC');
    $query->condition('FC.fertilizer_case_id',$id,'=');
    $query->fields('FC',array('file_id1','file_id2','file_id3','file_id4','file_id5'));
    $file_ids = $query->execute()->fetchObject();
    return $file_ids;
}